<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小同住人员物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996  15899929162
// +----------------------------------------------------------------------
namespace app\controller\property\property\basic;

use think\App;
use app\controller\property\Base;
use app\common\services\CacheService;
use think\exception\ValidateException;
use app\validate\property\basic\PropertyBasicValidate;
use app\common\repositories\system\SystemConfigRepository;
use app\common\repositories\property\basic\PropertyLogRepository;
use app\common\repositories\property\basic\PropertyLabelRepository;
use app\common\repositories\property\basic\PropertyBasicRepository;


class PropertyBasic extends Base
{
    protected $repository;

    public function __construct(App $app, PropertyBasicRepository $repository)
    {
        parent::__construct($app);

        $this->repository = $repository;
        $this->assign([
            'addAuth' => property_auth('propertyBasicAdd'),
            'editAuth' => property_auth('propertyBasicEdit'),
            'delAuth' => property_auth('propertyBasicDel'),
            'detailAuth' => property_auth('propertyBasicDetail'),
        ]);
    }

    /**
     *
     * @return string|\think\response\Json|\think\response\View
     * @throws \Exception
     *
     * @author Amos
     * 2024-01-22 08:31
     */
    public function configProperty(SystemConfigRepository $systemConfigRepository)
    {
        if ($this->request->isPost()) {
            $systemConfigRepository->modifyConfig('property', $this->request->post(), $this->request->propertyId);
            return json()->data(['code' => 0, 'msg' => '修改成功']);
        } else {
            return $this->fetch('property/basic/basic_info', [
                'info' => $systemConfigRepository->getConfig($this->request->propertyId, 'property')
            ]);
        }
    }


    public function list()
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'keywords' => '',
                'is_show' => '',
            ]);
            [$page, $limit] = $this->getPage();
            $res = $this->repository->getPropertyList($where, $page, $limit, $this->request->userId);
            return json()->data(['code' => 0, 'data' => $res['list'], 'count' => $res['count']]);
        }
        return $this->fetch('property/basic/list');
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'name' => '',
                'code' => '',
                'address' => '',
                'picture' => '',
                'longitude' => '',
                'latitude' => '',
                'cover_area' => '',
                'building_area' => '',
                'service_tel' => '',
                'service_code' => '',
                'remark' => '',
                'label_id' => '',
            ]);
            $param['code'] = strtoupper($param['code']);
            validate(PropertyBasicValidate::class)->scene('add')->check($param);
            if ($this->repository->fieldExists('name', $param['name'])) {
                return $this->error($param['name'] . ' 已存在');
            }
            if ($this->repository->fieldExists('code', $param['code'])) {
                return $this->error($param['code'] . ' 物业编码已存在');
            }
            try {
                $param['add_uid'] = $this->request->userId;
                $param['label_id'] = str_replace(['[', ']'], '', $param['label_id']);
                $param['label_id'] = array_filter(explode(',', $param['label_id']));
                $res = $this->repository->addInfo($param, $this->request->userId);
                if ($res) {
                    return $this->success('添加成功');
                } else {
                    return $this->error('添加失败');
                }
            } catch (\Exception $e) {
                exception_log('添加物业失败', $e);
                return $this->error('网络失败');
            }
        } else {
            $propertyLabelRepository = app()->make(PropertyLabelRepository::class);
            $labelData = $propertyLabelRepository->getLabelData(['is_show' => 1]);
            return $this->fetch('property/basic/add', [
                'labelData' => $labelData,
                'code' => $this->repository->getCoce(5)
            ]);
        }

    }


    public function edit()
    {
        $id = (int)$this->request->param('id');
        if (!$id) {
            return $this->error('参数错误');
        }
        $info = $this->repository->getDetail($id);
        if (!$info) {
            return $this->error('信息错误');
        }
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'name' => '',
                'address' => '',
                'picture' => '',
                'longitude' => '',
                'latitude' => '',
                'cover_area' => '',
                'building_area' => '',
                'service_tel' => '',
                'service_code' => '',
                'remark' => '',
                'label_id' => '',
            ]);
            validate(PropertyBasicValidate::class)->scene('edit')->check($param);
            if ($this->repository->fieldExists('name', $param['name'], $id)) {
                return $this->error($param['name'] . ' 已存在');
            }
            try {
                $param['label_id'] = str_replace(['[', ']'], '', $param['label_id']);
                $param['label_id'] = array_filter(explode(',', $param['label_id']));
                $res = $this->repository->editInfo($info, $param, $this->request->userId);
                if ($res) {
                    return $this->success('修改成功');
                } else {
                    return $this->error('修改失败');
                }
            } catch (\Exception $e) {
                exception_log('修改失败', $e);
                return $this->error('网络错误');
            }
        } else {
            $propertyLabelRepository = app()->make(PropertyLabelRepository::class);
            $labelData = $propertyLabelRepository->getLabelData(['is_show' => 1]);
            return $this->fetch('property/basic/edit', [
                'info' => $info,
                'labelData' => $labelData,
            ]);
        }
    }

    public function del()
    {
        $ids = (array)$this->request->param('ids');
        try {
            $data = $this->repository->batchDelete($ids, $this->request->userId);
            if ($data) {
                return $this->success('删除成功');
            } else {
                return $this->error('删除失败');
            }
        } catch (\Exception $e) {
            return $this->error('网络失败');
        }
    }


    public function detail()
    {
        $propertyId = (int)$this->request->param('property_id');
        if ($propertyId <= 0) {
            return $this->error('参数错误');
        }
        $info = $this->repository->getDetail($propertyId);
        if ($info['id'] <= 0) {
            return $this->error('物业信息不存在');
        }
        return $this->fetch('property/basic/detail', [
            'info' => $info,
            'propertyLogAuth' => property_auth('propertyLogList'),
        ]);
    }

    ## 物业日志
    public function propertyLog(PropertyLogRepository $logRepository)
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'property_id' => '',
            ]);
            [$page, $limit] = $this->getPage();
            $res = $logRepository->getpropertyList($where, $page, $limit);
            return json()->data(['code' => 0, 'data' => $res['list'], 'count' => $res['count']]);
        }
    }
}